package xcmg.device.service.company;

import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExportUtil;
import xcmg.device.infra.FileUtil;
import xcmg.device.infra.enums.CompanyDealerStatusEnum;
import xcmg.device.service.vo.FunctionResult;
import xcmg.device.service.vo.company.CompanyDealerVO;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.PageHelperPlus;
import yb.ecp.fast.infra.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class CompanyDealerLimitService {

    @Autowired
    private CompanyDealerMapper companyDealerMapper;

    @Autowired
    private HttpServletResponse response;

    @Value("${spring.file.download.path}")
    private String filePath;

    private  String templateExcelFileName="CompanyDealerLimit.xls";

    public PageCommonVO list(SearchCommonVO<CompanyDealerVO> condition) {
        PageCommonVO pageCommonVO = new PageCommonVO();
        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<CompanyDealerDO> doList = companyDealerMapper.list(condition.getFilters());
        List<CompanyDealerVO> voList = new ArrayList<>();
        for (CompanyDealerDO companyDealerDO : doList) {
            if (companyDealerDO == null) {
                continue;
            }
            voList.add(getVO(companyDealerDO));
        }
        pageCommonVO.setPageInfo(new PageInfo(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    public FunctionResult importLimit(MultipartFile file, String orgId) throws Exception{
        FunctionResult result=new FunctionResult();
        //Workbook wb = WorkbookFactory.create(in);
        Workbook wb;//同时兼容Excel-2003及Excel-2007
        try {
            InputStream in = file.getInputStream();
            wb = new HSSFWorkbook(in);
        } catch (Exception ex) {
            // 解决read error异常
            // in = new FileInputStream(file);
            InputStream in = file.getInputStream();
            wb = new XSSFWorkbook(in);
        }
        Sheet sheet=wb.getSheetAt(0);
        int totalRow=sheet.getLastRowNum();
        if(totalRow<2){
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        int totalCell=sheet.getRow(1).getLastCellNum();
        if(totalCell!=4){
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        List<CompanyDealerVO> errorDetailVOList=new ArrayList<>();
        boolean success;
        for (int i=2;i<=totalRow;i++){
            //HSSFRow curRow=sheet.getRow(i);
            Row curRow=sheet.getRow(i);
            CompanyDealerVO detailVO=new CompanyDealerVO();
            if(curRow==null){
                continue;
            }
            String dealerCode = getCellValue(curRow, 1);
            String limit = getCellValue(curRow, 3);
            if(StringUtil.isNullOrEmpty(dealerCode)&&StringUtil.isNullOrEmpty(limit)){
                break;
            }
            if(StringUtil.isNullOrEmpty(dealerCode)){
                detailVO.setErrorRow(i+1);
                detailVO.setRemark("客户编码不能为空");
                errorDetailVOList.add(detailVO);
                continue;
            }
            if(StringUtil.isNullOrEmpty(limit)){
                detailVO.setErrorRow(i+1);
                detailVO.setRemark("额度不能为空，客户编码："+dealerCode);
                errorDetailVOList.add(detailVO);
                continue;
            }
            if(!isInteger(limit) || "0".equals(limit)){
                detailVO.setErrorRow(i+1);
                detailVO.setRemark("额度格式不正确，客户编码："+dealerCode);
                errorDetailVOList.add(detailVO);
                continue;
            }
            BigDecimal realLimit = new BigDecimal(limit);
            if(realLimit.compareTo(BigDecimal.valueOf(999999999)) > 0){
                detailVO.setErrorRow(i+1);
                detailVO.setRemark("额度过大，客户编码："+dealerCode);
                errorDetailVOList.add(detailVO);
                continue;
            }
            CompanyDealerDO dealerDO = companyDealerMapper.itemByDealerCode(orgId, dealerCode);
            if(dealerDO == null){
                detailVO.setErrorRow(i+1);
                detailVO.setRemark("客户不存在，客户编码："+dealerCode);
                errorDetailVOList.add(detailVO);
                continue;
            }
            success = companyDealerMapper.updateTotalLimit(realLimit, dealerDO.getId())>0;
            if(!success){
                detailVO.setErrorRow(i+1);
                detailVO.setRemark("更新失败，客户编码："+dealerCode);
                errorDetailVOList.add(detailVO);
                continue;
            }
        }

        if(ListUtil.isNullOrEmpty(errorDetailVOList)){
            result.setValue(new ArrayList<>());
            result.setCode(ErrorCode.Success);
        }else {
            result.setValue(errorDetailVOList);
            result.setCode(ErrorCode.IllegalArument);
        }
        return result;
    }

    private boolean isInteger(String str) {
        if (null == str || "".equals(str)) {
            return false;
        }
        try {
            BigDecimal decimal = new BigDecimal(str);
        }catch (Exception e){
            return false;
        }
        return true;
    }

    private String getCellValue(Row curRow, int i){
        String value = "";
        if(curRow.getCell(i) != null){
            curRow.getCell(i).setCellType(CellType.STRING);
            value = curRow.getCell(i).getStringCellValue();
        }
        return value;
    }

    public void downloadLimitExcel() throws Exception{
        FileUtil.downLoadFile(response, filePath, templateExcelFileName);
    }

    /**
     * @Author: WangKe
     * @Description: 更新客户总额度
     * @Date: 2018/9/11 0011
     */
    public ErrorCode updateLimit(List<CompanyDealerVO> dealerVOList)throws Exception{
        if(ListUtil.isNullOrEmpty(dealerVOList)){
            return ErrorCode.IllegalArument;
        }
        boolean success;
        for(CompanyDealerVO dealerVO : dealerVOList){
            if(dealerVO.getTotalLimit() == null){
                dealerVO.setTotalLimit(BigDecimal.ZERO);
            }
            if(dealerVO.getEnableLimit() == 1 && dealerVO.getTotalLimit().compareTo(dealerVO.getOldLimit()) != 0){
                if(dealerVO.getTotalLimit().compareTo(dealerVO.getUsedLimit()) < 0){
                    throw new Exception("总额度不能小于已用额度");
                }
                success = companyDealerMapper.updateTotalLimit(dealerVO.getTotalLimit(), dealerVO.getId())>0;
                if(!success){
                    throw new Exception("更新额度失败");
                }
            }
        }
        return ErrorCode.Success;
    }

    public CompanyDealerVO getVO(CompanyDealerDO companyDealerVO){
        if(companyDealerVO==null){
            return null;
        }
        CompanyDealerVO companyDealerDO = new CompanyDealerVO();
        BeanUtils.copyProperties(companyDealerVO, companyDealerDO);
        if(null!=companyDealerVO.getApplyStatus()){
            companyDealerDO.setApplyStatus(companyDealerVO.getApplyStatus());

            CompanyDealerStatusEnum dealerStatus = CompanyDealerStatusEnum.getDealerStatus(companyDealerVO.getApplyStatus());
            if(null!=dealerStatus) {
                companyDealerDO.setApplyStatusDesc(dealerStatus.getDesc());
            }
        }
        return companyDealerDO;
    }

    public void exportAll(CompanyDealerVO condition)throws Exception{
        PageHelperPlus.orderBy("create_date desc");
        invokeExport(companyDealerMapper.list(condition));
    }

    private void invokeExport(List<CompanyDealerDO> doList)throws Exception{
        String title = "客户额度导出";
        String[] rowsName = new String[]{"序号","客户编号","客户名称","客户代码","客户分类","客户简称",
                "已用额度","总额度"};
        List<Object[]>  dataList = new ArrayList<>();
        Object[] objs;
        for (int i = 0; i < doList.size(); i++) {
            CompanyDealerDO exportDO = doList.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i+1;
            objs[1] = exportDO.getDealerCode();
            objs[2] = exportDO.getCompanyName();
            objs[3] = exportDO.getDealerOrgId();
            objs[4] = exportDO.getDealerClassName();
            objs[5] = exportDO.getShortName();
            objs[6] = exportDO.getUsedLimit();
            objs[7] = exportDO.getTotalLimit();
            dataList.add(objs);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode updateEnableLimit(List<String> ids, Integer enable) throws Exception{
        if(ListUtil.isNullOrEmpty(ids)){
            return ErrorCode.IllegalArument;
        }
        List<Long> list = new ArrayList<>();
        for(String str : ids){
            list.add(Long.valueOf(str));
        }
        return companyDealerMapper.updateEnableLimit(enable, list)>0?ErrorCode.Success:ErrorCode.Failure;
    }
}
